import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';

import { Hero } from '../../commons/hero';
import { HeroService } from '../../services/hero.service';

@Component({
  selector: 'hero-detail-component',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent {
  @Input()
  hero: Hero;

  @Output()
  aaaaa = new EventEmitter();

  navigated = false;

  constructor(
    private heroService: HeroService,
    private route: ActivatedRoute) {
  }

  ngOnInit(): void {
    this.route.params.forEach((params: Params) => {
      if (params['id'] !== undefined) {
        let id = parseInt(params['id']);
        this.navigated = true;
        this.hero = this.heroService.getHero(id)
      } else {
        this.navigated = false;
        this.hero = new Hero();
      }
    });
  }

  save(): void {
    console.log("1")
    let saveSuccess = this.heroService.save(this.hero);
    if (saveSuccess) {
      this.goBack(this.hero);
    }
  }

  goBack(savedHero: Hero = null): void {
    // emit()触发，通知heroes.component组件
    // 执行heroes.component组件中的close()方法
    // 相当于在子组件hero-detail.component去调用父组件
    // heroes.component中的方法
    // 使用子组件时，通过属性配置让子组件中的EventEmitter对象(aaaaa)
    // 和父组件中的方法（close()）联系起来，比如：(aaaaa)="close($event)
    this.aaaaa.emit(savedHero);
    if (this.navigated) {
      window.history.back();
    }
  }
}